package com.leetcode;

public class Leetcode191 {
    /*
    //solution 1: 位运算，按照int最大的位数，一次移动一位
    public int hammingWeight(int n) {
        int res = 0;
        for (int i = 0; i < 32; i++) {
            if ((n & (1 << i)) != 0) {
                res++;
            }
        }
        return res;
    }
*/
    //solution 2: 位运算优化，n = n & (n - 1) 每次会将最低位的“1”给清零
    public int hammingWeight(int n) {
        int res = 0;
        while (n != 0) {
            n = n & (n - 1);
            res += 1;
        }

        return res;
    }

    public static void main(String[] args) {
        Leetcode191 leetcode191 = new Leetcode191();
        System.out.println(leetcode191.hammingWeight(15));
    }
}
